<!DOCTYPE html>

































































<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<link rel="shortcut icon" type="image/x-icon" href="../../../favicon.ico" />
<title>Implementing In-app Billing | Android Developers</title>
<link href="../../../assets/android-developer-docs-devguide.css" rel="stylesheet" type="text/css" />
<script src="../../../assets/search_autocomplete.js" type="text/javascript"></script>
<script src="../../../assets/jquery-resizable.min.js" type="text/javascript"></script>
<script src="../../../assets/android-developer-docs.js" type="text/javascript"></script>
<script src="../../../assets/prettify.js" type="text/javascript"></script>
<script type="text/javascript">
  setToRoot("../../../");
</script>
<noscript>
  <style type="text/css">
    html,body{overflow:auto;}
    #body-content{position:relative; top:0;}
    #doc-content{overflow:visible;border-left:3px solid #666;}
    #side-nav{padding:0;}
    #side-nav .toggle-list ul {display:block;}
    #resize-packages-nav{border-bottom:3px solid #666;}
  </style>
</noscript>
</head>
<body class="gc-documentation">

  <div id="header">
      <div id="headerLeft">
          <a href="../../../index.html" tabindex="-1"><img
              src="../../../assets/images/bg_logo.png" alt="Android Developers" /></a>
          <ul id="header-tabs" class="guide">
    
	<li id="home-link"><a href="../../../offline.html">
	
		<span class="en">Home</span>
		<span style="display:none" class="de">Startseite</span>
		<span style="display:none" class="es"></span>
		<span style="display:none" class="fr"></span>
		<span style="display:none" class="it"></span>
		<span style="display:none" class="ja">ホーム</span>
		<span style="display:none" class="zh-CN">主页</span>
		<span style="display:none" class="zh-TW">首頁</span>
	
	</a></li>
	<li id="sdk-link"><a href="../../../sdk/index.html">
		<span class="en">SDK</span>
	</a></li>
	<li id="guide-link"><a href="../../../guide/index.html" onClick="return loadLast('guide')">
	
		<span class="en">Dev Guide</span>
		<span style="display:none" class="de">Handbuch</span>
		<span style="display:none" class="es">Guía</span>
		<span style="display:none" class="fr">Guide</span>
		<span style="display:none" class="it">Guida</span>
		<span style="display:none" class="ja">開発ガイド</span>
		<span style="display:none" class="zh-CN">开发人员指南</span>
		<span style="display:none" class="zh-TW">開發指南</span>
	
	</a></li>
	<li id="reference-link"><a href="../../../reference/packages.html" onClick="return loadLast('reference')">
	
		<span class="en">Reference</span>
		<span style="display:none" class="de">Referenz</span>
		<span style="display:none" class="es">Referencia</span>
		<span style="display:none" class="fr">Référence</span>
		<span style="display:none" class="it">Riferimento</span>
		<span style="display:none" class="ja">リファレンス</span>
		<span style="display:none" class="zh-CN">参考</span>
		<span style="display:none" class="zh-TW">參考資料</span>
	
	</a></li>
	<li id="resources-link"><a href="../../../resources/index.html" onClick="return loadLast('resources')">
	
		<span class="en">Resources</span>
		<span style="display:none" class="de"></span>
		<span style="display:none" class="es"></span>
		<span style="display:none" class="fr"></span>
		<span style="display:none" class="it"></span>
    		<span style="display:none" class="ja"></span>
		<span style="display:none" class="zh-CN"></span>
		<span style="display:none" class="zh-TW"></span>
	
	</a></li>
	<li id="videos-link"><a href="../../../videos/index.html" onClick="return loadLast('videos')">
	
		<span class="en">Videos</span>
		<span style="display:none" class="de"></span>
		<span style="display:none" class="es"></span>
		<span style="display:none" class="fr"></span>
		<span style="display:none" class="it"></span>
		<span style="display:none" class="ja">ビデオ</span>
		<span style="display:none" class="zh-CN"></span>
		<span style="display:none" class="zh-TW"></span>
	
	</a></li>
	<li><a href="http://android-developers.blogspot.com" onClick="return requestAppendHL(this.href)">
	
		<span class="en">Blog</span>
		<span style="display:none" class="de"></span>
		<span style="display:none" class="es"></span>
		<span style="display:none" class="fr"></span>
		<span style="display:none" class="it"></span>
		<span style="display:none" class="ja">ブログ</span>
		<span style="display:none" class="zh-CN">博客</span>
		<span style="display:none" class="zh-TW">網誌</span>
	
	</a></li>


     
</ul>
     
      </div>
      <div id="headerRight">
          <div id="headerLinks">
          
          <a href="http://www.android.com">Android.com</a>
          </div>
  <div id="search" >
      <div id="searchForm">
          <form accept-charset="utf-8" class="gsc-search-box" 
                onsubmit="return submit_search()">
            <table class="gsc-search-box" cellpadding="0" cellspacing="0"><tbody>
                <tr>
                  <td class="gsc-input">
                    <input id="search_autocomplete" class="gsc-input" type="text" size="33" autocomplete="off"
                      title="search developer docs" name="q"
                      value="search developer docs"
                      onFocus="search_focus_changed(this, true)"
                      onBlur="search_focus_changed(this, false)"
                      onkeydown="return search_changed(event, true, '../../../')"
                      onkeyup="return search_changed(event, false, '../../../')" />
                  <div id="search_filtered_div" class="no-display">
                      <table id="search_filtered" cellspacing=0>
                      </table>
                  </div>
                  </td>
                  <td class="gsc-search-button">
                    <input type="submit" value="Search" title="search" id="search-button" class="gsc-search-button" />
                  </td>
                  <td class="gsc-clear-button">
                    <div title="clear results" class="gsc-clear-button">&nbsp;</div>
                  </td>
                </tr></tbody>
              </table>
          </form>
      </div><!-- searchForm -->
  </div><!-- search -->
      </div><!-- headerRight -->
      <script type="text/javascript">
        <!--  
        changeTabLang(getLangPref());
        //-->
      </script>
  </div><!-- header -->

  <div class="g-section g-tpl-240" id="body-content">
    <div class="g-unit g-first" id="side-nav">
      <div id="devdoc-nav">
<ul>

  <li>
    <h2><span class="en">Android Basics</span>
        <span class="de" style="display:none">Einführung in Android</span>
        <span class="es" style="display:none">Información básica sobre Android</span>
        <span class="fr" style="display:none">Présentation d'Android</span>
        <span class="it" style="display:none">Nozioni di base su Android</span>
        <span class="ja" style="display:none">Android の基本</span>
        <span class="zh-CN" style="display:none">Android 基础知识</span>
        <span class="zh-TW" style="display:none">Android 簡介</span>
    </h2>
    <ul>
      <li><a href="../../../guide/basics/what-is-android.html">
        <span class="en">What Is Android?</span>
        <span class="de" style="display:none">Was ist Android?</span>
        <span class="es" style="display:none">¿Qué es Android?</span>
        <span class="fr" style="display:none">Qu'est-ce qu'Android&nbsp;?</span>
        <span class="it" style="display:none">Che cos'è Android?</span>
        <span class="ja" style="display:none">Android とは</span>
        <span class="zh-CN" style="display:none">Android 是什么？</span>
        <span class="zh-TW" style="display:none">什麼是 Android？</span>
          </a></li>
      <li><a href="../../../guide/topics/fundamentals.html">
        <span class="en">Application Fundamentals</span>
        <span class="de" style="display:none">Anwendungsgrundlagen</span>
        <span class="es" style="display:none">Fundamentos de las aplicaciones</span>
        <span class="fr" style="display:none">Principes de base des applications</span>
        <span class="it" style="display:none">Concetti fondamentali sulle applicazioni</span>
        <span class="ja" style="display:none">開発の基礎</span>
        <span class="zh-CN" style="display:none">应用程序基础</span>
        <span class="zh-TW" style="display:none">應用程式基本原理</span>
      </a></li>

  <!--  <li><a style="color:gray;">The Android SDK</a></li> -->
  <!--  <li><a style="color:gray;">Walkthrough for Developers</a></li> -->
      <!-- quick overview of what it's like to develop on Android -->
    </ul>
  </li>

  <li>
    <h2>
      <span class="en">Framework Topics</span>
      <span class="de" style="display:none">Framework-Themen</span>
      <span class="es" style="display:none">Temas sobre el framework</span>
      <span class="fr" style="display:none">Thèmes relatifs au framework</span>
      <span class="it" style="display:none">Argomenti relativi al framework</span>
      <span class="ja" style="display:none">フレームワーク トピック</span>
      <span class="zh-CN" style="display:none">框架主题</span>
      <span class="zh-TW" style="display:none">架構主題</span>
    </h2>
    <ul>
      <li class="toggle-list">
        <div><a href="../../../guide/topics/fundamentals/activities.html">
          <span class="en">Activities</span>
        </a></div>
        <ul>
          <li><a href="../../../guide/topics/fundamentals/fragments.html">
            <span class="en">Fragments</span>
          </a></li>
          <li><a href="../../../guide/topics/fundamentals/loaders.html">
            <span class="en">Loaders</span>
          </a></li>
          <li><a href="../../../guide/topics/fundamentals/tasks-and-back-stack.html">
            <span class="en">Tasks and Back Stack</span></a></li>
        </ul>
      </li>
      <li class="toggle-list">
        <div><a href="../../../guide/topics/fundamentals/services.html">
          <span class="en">Services</span>
        </a></div>
        <ul>
          <li><a href="../../../guide/topics/fundamentals/bound-services.html">
            <span class="en">Bound Services</span>
          </a></li>
        </ul>
      </li>
      <li><a href="../../../guide/topics/providers/content-providers.html">
            <span class="en">Content Providers</span>
          </a></li>
      <li><a href="../../../guide/topics/intents/intents-filters.html">
            <span class="en">Intents and Intent Filters</span>
          </a></li>
      <li><a href="../../../guide/topics/fundamentals/processes-and-threads.html">
            <span class="en">Processes and Threads</span>
          </a></li>
    </ul>


    <ul>
      <li class="toggle-list">
        <div><a href="../../../guide/topics/ui/index.html">
            <span class="en">User Interface</span>
          </a></div>
        <ul>
          <li><a href="../../../guide/topics/ui/declaring-layout.html">
               <span class="en">XML Layouts</span>
              </a></li>
          <li><a href="../../../guide/topics/ui/ui-events.html">
                <span class="en">Input Events</span>
              </a></li>
          <li><a href="../../../guide/topics/ui/menus.html">
               <span class="en">Menus</span>
              </a></li>
          <li><a href="../../../guide/topics/ui/actionbar.html">
               <span class="en">Action Bar</span>
              </a></li>
          <li><a href="../../../guide/topics/ui/dialogs.html">
                <span class="en">Dialogs</span>
              </a></li>
          <li class="toggle-list">
            <div><a href="../../../guide/topics/ui/notifiers/index.html">
                <span class="en">Notifications</span>
            </a></div>
            <ul>
              <li><a href="../../../guide/topics/ui/notifiers/toasts.html">
                <span class="en">Toast Notifications</span>
              </a></li>
              <li><a href="../../../guide/topics/ui/notifiers/notifications.html">
                <span class="en">Status Bar Notifications</span>
              </a></li>
            </ul>
          </li>
          <li><a href="../../../guide/topics/ui/drag-drop.html">
                <span class="en">Drag and Drop</span>
              </a></li>
          <li><a href="../../../guide/topics/ui/themes.html">
                <span class="en">Styles and Themes</span>
              </a></li>
          <li><a href="../../../guide/topics/ui/custom-components.html">
                <span class="en">Custom Components</span>
              </a></li>
          <li><a href="../../../guide/topics/ui/binding.html">
                <span class="en">Binding to Data with AdapterView</span>
              </a></li>
          <li><a href="../../../guide/topics/ui/layout-objects.html">
                <span class="en">Common Layout Objects</span>
              </a></li>
          <li><a href="../../../guide/topics/ui/how-android-draws.html">
                <span class="en">How Android Draws Views</span>
              </a></li>
        </ul>
      </li><!-- end of User Interface -->

      <li class="toggle-list">
        <div><a href="../../../guide/topics/resources/index.html">
               <span class="en">Application Resources</span>
             </a></div>
        <ul>
          <li><a href="../../../guide/topics/resources/providing-resources.html">
                <span class="en">Providing Resources</span>
              </a></li>
          <li><a href="../../../guide/topics/resources/accessing-resources.html">
                <span class="en">Accessing Resources</span>
              </a></li>
          <li><a href="../../../guide/topics/resources/runtime-changes.html">
                <span class="en">Handling Runtime Changes</span>
              </a></li>
          <li><a href="../../../guide/topics/resources/localization.html">
                <span class="en">Localization</span>
              </a></li>
          <li class="toggle-list">
            <div><a href="../../../guide/topics/resources/available-resources.html">
              <span class="en">Resource Types</span>
            </a></div>
            <ul>
              <li><a href="../../../guide/topics/resources/animation-resource.html">Animation</a></li>
              <li><a href="../../../guide/topics/resources/color-list-resource.html">Color State List</a></li>
              <li><a href="../../../guide/topics/resources/drawable-resource.html">Drawable</a></li>
              <li><a href="../../../guide/topics/resources/layout-resource.html">Layout</a></li>
              <li><a href="../../../guide/topics/resources/menu-resource.html">Menu</a></li>
              <li><a href="../../../guide/topics/resources/string-resource.html">String</a></li>
              <li><a href="../../../guide/topics/resources/style-resource.html">Style</a></li>
              <li><a href="../../../guide/topics/resources/more-resources.html">More Types</a></li>
            </ul>
          </li><!-- end of resource types -->
        </ul>
      </li><!-- end of app resources -->
      <li class="toggle-list">
        <div><a href="../../../guide/topics/data/data-storage.html">
            <span class="en">Data Storage</span>
          </a></div>
          <ul>
            <li><a href="../../../guide/topics/data/backup.html">
                <span class="en">Data Backup</span>
              </a>
            </li>
          </ul>
      </li>
      <li><a href="../../../guide/topics/security/security.html">
            <span class="en">Security and Permissions</span>
          </a></li>
      <li class="toggle-list">
        <div><a href="../../../guide/topics/manifest/manifest-intro.html">
          <span class="en">The AndroidManifest.xml File</span>
        </a></div>
        <ul>
          <li><a href="../../../guide/topics/manifest/action-element.html">&lt;action&gt;</a></li>
          <li><a href="../../../guide/topics/manifest/activity-element.html">&lt;activity&gt;</a></li>
          <li><a href="../../../guide/topics/manifest/activity-alias-element.html">&lt;activity-alias&gt;</a></li>
          <li><a href="../../../guide/topics/manifest/application-element.html">&lt;application&gt;</a></li>
          <li><a href="../../../guide/topics/manifest/category-element.html">&lt;category&gt;</a></li>
          <li><a href="../../../guide/topics/manifest/compatible-screens-element.html">&lt;compatible-screens&gt;</a></li>
          <li><a href="../../../guide/topics/manifest/data-element.html">&lt;data&gt;</a></li>
          <li><a href="../../../guide/topics/manifest/grant-uri-permission-element.html">&lt;grant-uri-permission&gt;</a></li>
          <li><a href="../../../guide/topics/manifest/instrumentation-element.html">&lt;instrumentation&gt;</a></li>
          <li><a href="../../../guide/topics/manifest/intent-filter-element.html">&lt;intent-filter&gt;</a></li>
          <li><a href="../../../guide/topics/manifest/manifest-element.html">&lt;manifest&gt;</a></li>
          <li><a href="../../../guide/topics/manifest/meta-data-element.html">&lt;meta-data&gt;</a></li>
          <li><a href="../../../guide/topics/manifest/path-permission-element.html">&lt;path-permission&gt;</a></li>
          <li><a href="../../../guide/topics/manifest/permission-element.html">&lt;permission&gt;</a></li>
          <li><a href="../../../guide/topics/manifest/permission-group-element.html">&lt;permission-group&gt;</a></li>
          <li><a href="../../../guide/topics/manifest/permission-tree-element.html">&lt;permission-tree&gt;</a></li>
          <li><a href="../../../guide/topics/manifest/provider-element.html">&lt;provider&gt;</a></li>
          <li><a href="../../../guide/topics/manifest/receiver-element.html">&lt;receiver&gt;</a></li>
          <li><a href="../../../guide/topics/manifest/service-element.html">&lt;service&gt;</a></li>
          <li><a href="../../../guide/topics/manifest/supports-gl-texture-element.html">&lt;supports-gl-texture&gt;</a></li>
          <li><a href="../../../guide/topics/manifest/supports-screens-element.html">&lt;supports-screens&gt;</a></li><!-- ##api level 4## -->
          <li><a href="../../../guide/topics/manifest/uses-configuration-element.html">&lt;uses-configuration&gt;</a></li>
          <li><a href="../../../guide/topics/manifest/uses-feature-element.html">&lt;uses-feature&gt;</a></li> <!-- ##api level 4## -->
          <li><a href="../../../guide/topics/manifest/uses-library-element.html">&lt;uses-library&gt;</a></li>
          <li><a href="../../../guide/topics/manifest/uses-permission-element.html">&lt;uses-permission&gt;</a></li>
          <li><a href="../../../guide/topics/manifest/uses-sdk-element.html">&lt;uses-sdk&gt;</a></li>
        </ul>
      </li><!-- end of the manifest file -->
    </ul>

    <ul>
    <li class="toggle-list">
        <div><a href="../../../guide/topics/graphics/index.html">
            <span class="en">Graphics</span>
          </a><span class="new-child">new!</span></div>
        <ul>
          <li><a href="../../../guide/topics/graphics/2d-graphics.html">
              <span class="en">Canvas and Drawables</span></a></li>
          <li><a href="../../../guide/topics/graphics/hardware-accel.html">
              <span class="en">Hardware Acceleration</span></a>
            <span class="new">new!</span></li>
          <li><a href="../../../guide/topics/graphics/opengl.html">
              <span class="en">OpenGL</span>
            </a><span class="new">updated</span></li>
        </ul>
      </li>
      <li class="toggle-list">
        <div><a href="../../../guide/topics/graphics/animation.html">
            <span class="en">Animation</span>
          </a></div>
        <ul>
          <li><a href="../../../guide/topics/graphics/prop-animation.html">
              <span class="en">Property Animation</span></a></li>
          <li><a href="../../../guide/topics/graphics/view-animation.html">
              <span class="en">View Animation</span></a></li>
          <li><a href="../../../guide/topics/graphics/drawable-animation.html">
              <span class="en">Drawable Animation</span></a></li>
        </ul>
      </li>
      <li class="toggle-list">
	        <div><a href="../../../guide/topics/renderscript/index.html">
	            <span class="en">RenderScript</span>
	          </a></div>
	        <ul>
	          <li><a href="../../../guide/topics/renderscript/graphics.html">
	                <span class="en">Graphics</span>
	              </a>
	          </li>
	          <li><a href="../../../guide/topics/renderscript/compute.html">
	                <span class="en">Compute</span>
	              </a>
	          </li>
	        </ul>
  	  </li>

      <li class="toggle-list">
          <div><a href="../../../guide/topics/media/index.html">
            <span class="en">Multimedia and Camera</span>
          </a><span class="new">updated</span></div>
          <ul>
            <li><a href="../../../guide/topics/media/mediaplayer.html">
                  <span class="en">Media Playback</span></a>
                </li>
            <li><a href="../../../guide/topics/media/jetplayer.html">
                  <span class="en">JetPlayer</span></a>
                </li>
            <li><a href="../../../guide/topics/media/camera.html">
                  <span class="en">Camera</span></a>
                  <span class="new">new!</span>
                </li>
            <li><a href="../../../guide/topics/media/audio-capture.html">
                  <span class="en">Audio Capture</span></a>
                </li>
          </ul>
      </li>
      <li>
        <a href="../../../guide/topics/clipboard/copy-paste.html">
            <span class="en">Copy and Paste</span>
        </a></li>
  <!--<li class="toggle-list">
        <div><a style="color:gray;">Sensors</a></div>
          <ul>
            <li><a style="color:gray;">Camera</a></li>
            <li><a style="color:gray;">Compass</a></li>
            <li><a style="color:gray;">Accelerometer</a></li>
          </ul>
      </li> -->
      <li class="toggle-list">
        <div><a href="../../../guide/topics/location/index.html">
               <span class="en">Location and Maps</span>
             </a></div>
        <ul>
          <li><a href="../../../guide/topics/location/obtaining-user-location.html">
                <span class="en">Obtaining User Location</span>
              </a></li>
        </ul>
      </li>
  <!--<li class="toggle-list">
        <div><a style="color:gray;">Wireless Controls</a></div>
          <ul>
            <li><a style="color:gray;">Wi-Fi</a></li>
          </ul>
      </li> -->
  <!--<li><a style="color:gray;">Localization</a></li>  -->
      <li><a href="../../../guide/topics/appwidgets/index.html">
            <span class="en">App Widgets</span></a>
          </li>
      <li><a href="../../../guide/topics/wireless/bluetooth.html">
            <span class="en">Bluetooth</span></a>
          </li>
      <li><a href="../../../guide/topics/nfc/index.html">
            <span class="en">Near Field Communication</span>
          </a></li>
      <li class="toggle-list">
          <div><a href="../../../guide/topics/usb/index.html">
            <span class="en">USB</span></a>
          </div>
            <ul>
              <li><a href="../../../guide/topics/usb/accessory.html">Accessory</a></li>
              <li><a href="../../../guide/topics/usb/host.html">Host</a></li>
              <li><a href="../../../guide/topics/usb/adk.html">Open Accessory Dev Kit</a></li>
            </ul>
          </li>

       <li><a href="../../../guide/topics/network/sip.html">
            <span class="en">Session Initiation Protocol</span>
          </a></li>
      <li class="toggle-list">
        <div><a href="../../../guide/topics/search/index.html">
            <span class="en">Search</span>
          </a></div>
          <ul>
            <li><a href="../../../guide/topics/search/search-dialog.html">Creating a Search Interface</a></li>
            <li><a href="../../../guide/topics/search/adding-recent-query-suggestions.html">Adding Recent Query Suggestions</a></li>
            <li><a href="../../../guide/topics/search/adding-custom-suggestions.html">Adding Custom Suggestions</a></li>
            <li><a href="../../../guide/topics/search/searchable-config.html">Searchable Configuration</a></li>
          </ul>
      </li>
      <li><a href="../../../guide/topics/admin/device-admin.html">
            <span class="en">Device Administration</span></a>
      </li>
      <li class="toggle-list">
           <div>
                <a href="../../../guide/topics/testing/index.html">
                   <span class="en">Testing</span>
               </a>
           </div>
           <ul>
              <li>
                <a href="../../../guide/topics/testing/testing_android.html">
                <span class="en">Testing Fundamentals</span></a>
              </li>
              <li>
                <a href="../../../guide/topics/testing/activity_testing.html">
                <span class="en">Activity Testing</span></a>
              </li>
              <li>
                <a href="../../../guide/topics/testing/contentprovider_testing.html">
                <span class="en">Content Provider Testing</span></a>
              </li>
              <li>
                <a href="../../../guide/topics/testing/service_testing.html">
                <span class="en">Service Testing</span></a>
              </li>
              <li>
                <a href="../../../guide/topics/testing/what_to_test.html">
                <span class="en">What To Test</span></a>
              </li>
           </ul>
      </li>
    </ul>
  </li>

  <li>
    <h2>
      <span class="en">Android Market Topics</span>
    </h2>
    <ul>
      <li><a href="../../../guide/publishing/licensing.html">
          <span class="en">Application Licensing</span></a>
      </li>
      <li class="toggle-list">
        <div><a href="../../../guide/market/billing/index.html">
            <span class="en">In-app Billing</span></a>
        </div>
        <ul>
          <li><a href="../../../guide/market/billing/billing_overview.html">
              <span class="en">In-app Billing Overview</span></a>
          </li>
          <li><a href="../../../guide/market/billing/billing_integrate.html">
              <span class="en">Implementing In-app Billing</span></a>
          </li>
          <li><a href="../../../guide/market/billing/billing_best_practices.html">
              <span class="en">Security and Design</span></a>
          </li>
          <li><a href="../../../guide/market/billing/billing_testing.html">
              <span class="en">Testing In-app Billing</span></a>
          </li>
          <li><a href="../../../guide/market/billing/billing_admin.html">
              <span class="en">Administering In-app Billing</span></a>
          </li>
          <li><a href="../../../guide/market/billing/billing_reference.html">
              <span class="en">In-app Billing Reference</span></a>
          </li>
        </ul>
      </li>
      <li><a href="../../../guide/appendix/market-filters.html">
          <span class="en">Market Filters</span></a>
      </li>
      <li><a href="../../../guide/market/publishing/multiple-apks.html">
          <span class="en">Multiple APK Support</span></a>
      </li>
    </ul>
  </li>


  <li>
    <h2><span class="en">Developing</span>
               <span class="de" style="display:none">Entwicklung</span>
               <span class="es" style="display:none">Desarrollo</span>
               <span class="fr" style="display:none">Développement</span>
               <span class="it" style="display:none">Sviluppo</span>
               <span class="ja" style="display:none">開発</span>
               <span class="zh-CN" style="display:none">开发</span>
               <span class="zh-TW" style="display:none">開發</span>
    </h2>
    <ul>
  <!--<li><a href="">Developing for Android</a></li>
      signing, upgrading, selecting a package name, select device profile, touch, trackball, dpad available, etc. -->
      <li>
        <a href="../../../guide/developing/index.html">
        <span class="en">Introduction</span></a>
      </li>

      <li class="toggle-list">
        <div>
           <a href="../../../guide/developing/devices/index.html">
                <span class="en">Managing Virtual Devices</span>
            </a>
        </div>
        <ul>
          <li>
            <a href="../../../guide/developing/devices/managing-avds.html">
              <span class="en">With AVD Manager</span>
            </a>
          </li>
          <li>
            <a href="../../../guide/developing/devices/managing-avds-cmdline.html">
              <span class="en">From the Command Line</span>
            </a>
          </li>
          <li>
           <a href="../../../guide/developing/devices/emulator.html">
                <span class="en">Using the Android Emulator</span>
            </a>
          </li>
        </ul>
      </li>
      <li>
        <a href="../../../guide/developing/device.html">
          <span class="en">Using Hardware Devices</span>
        </a>
      </li>

      <li class="toggle-list">
        <div>
          <a href="../../../guide/developing/projects/index.html">
            <span class="en">Managing Projects</span>
          </a>
        </div>
        <ul>
          <li>
            <a href="../../../guide/developing/projects/projects-eclipse.html">
              <span class="en">From Eclipse with ADT</span>
            </a>
          </li>
          <li>
            <a href="../../../guide/developing/projects/projects-cmdline.html">
                <span class="en">From the Command Line</span>
            </a>
          </li>
        </ul>
      </li>

      <li class="toggle-list">
        <div>
          <a href="../../../guide/developing/building/index.html">
            <span class="en">Building and Running</span>
          </a>
        </div>
        <ul>
          <li><a href="../../../guide/developing/building/building-eclipse.html">
            <span class="en">From Eclipse with ADT</span>
          </a></li>
          <li><a href="../../../guide/developing/building/building-cmdline.html">
            <span class="en">From the Command Line</span></a></li>
        </ul>
      </li>

      <li class="toggle-list">
        <div>
          <a href="../../../guide/developing/debugging/index.html">
            <span class="en">Debugging</span>
          </a>
        </div>
        <ul>
          <li>
            <a href="../../../guide/developing/debugging/debugging-projects.html">
                <span class="en">From Eclipse with ADT</span>
            </a>
          </li>
          <li>
            <a href="../../../guide/developing/debugging/debugging-projects-cmdline.html">
                <span class="en">From Other IDEs</span>
            </a>
          </li>
          <li>
            <a href="../../../guide/developing/debugging/ddms.html">
              <span class="en">Using DDMS</span>
            </a>
          </li>
          <li>
            <a href="../../../guide/developing/debugging/debugging-log.html">
                <span class="en">Reading and Writing Logs</span>
            </a>
          </li>
          <li>
            <a href="../../../guide/developing/debugging/debugging-ui.html">
                <span class="en">Debugging and Profiling UIs</span>
            </a>
          </li>
          <li>
            <a href="../../../guide/developing/debugging/debugging-tracing.html">
                <span class="en">Profiling with Traceview and dmtracedump</span>
            </a>
          </li>
          <li>
            <a href="../../../guide/developing/debugging/debugging-devtools.html">
                <span class="en">Using the Dev Tools App</span>
            </a>
          </li>
        </ul>
      </li>

      <li class="toggle-list">
           <div>
                <a href="../../../guide/developing/testing/index.html">
                   <span class="en">Testing</span>
               </a>
           </div>
           <ul>
              <li>
                <a href="../../../guide/developing/testing/testing_eclipse.html">
                  <span class="en">From Eclipse with ADT</span>
                </a>
              </li>

              <li>
                <a href="../../../guide/developing/testing/testing_otheride.html">
                  <span class="en">From Other IDEs</span>
                </a>
              </li>
           </ul>
         </li>

         <li class="toggle-list">
        <div><a href="../../../guide/developing/tools/index.html">
            <span class="en">Tools</span>
          </a></div>
        <ul>
          <li><a href="../../../guide/developing/tools/adb.html">adb</a></li>
          <li><a href="../../../guide/developing/tools/adt.html">ADT</a></li>
          <li><a href="../../../guide/developing/tools/android.html">android</a></li>
          <li><a href="../../../guide/developing/tools/bmgr.html">bmgr</a>
          <li><a href="../../../guide/developing/tools/dmtracedump.html">dmtracedump</a></li>
          <li><a href="../../../guide/developing/tools/draw9patch.html">Draw
          9-Patch</a></li>
          <li><a href="../../../guide/developing/tools/emulator.html">Emulator</a></li>
          <li><a href="../../../guide/developing/tools/etc1tool.html">etc1tool</a></li>
          <li><a href="../../../guide/developing/tools/hierarchy-viewer.html">Hierarchy Viewer</a></li>
          <li><a href="../../../guide/developing/tools/hprof-conv.html">hprof-conv</a></li>
          <li><a href="../../../guide/developing/tools/layoutopt.html">layoutopt</a></li>
          <li><a href="../../../guide/developing/tools/logcat.html">logcat</a></li>
          <li><a href="../../../guide/developing/tools/mksdcard.html">mksdcard</a></li>
          <li><a href="../../../guide/developing/tools/monkey.html">Monkey</a></li>
          <li class="toggle-list">
            <div><a href="../../../guide/developing/tools/monkeyrunner_concepts.html">
              <span class="en">monkeyrunner</span>
            </a></div>
            <ul>
              <li><a href="../../../guide/developing/tools/MonkeyDevice.html">
                <span class="en">MonkeyDevice</span>
                </a></li>
              <li><a href="../../../guide/developing/tools/MonkeyImage.html">
                <span class="en">MonkeyImage</span>
                </a></li>
              <li><a href="../../../guide/developing/tools/MonkeyRunner.html">
                <span class="en">MonkeyRunner</span>
                </a></li>
            </ul>
          </li>
          <li><a href="../../../guide/developing/tools/proguard.html">ProGuard</a></li>
          <li><a href="../../../guide/developing/tools/adb.html#sqlite">sqlite3</a></li>
          <li><a href="../../../guide/developing/tools/traceview.html">Traceview</a></li>
          <li><a href="../../../guide/developing/tools/zipalign.html">zipalign</a></li>
        </ul>
      </li>
    </ul>
  </li>

  <li>
    <h2><span class="en">Publishing</span>
        <span class="de" style="display:none">Veröffentlichung</span>
        <span class="es" style="display:none">Publicación</span>
        <span class="fr" style="display:none">Publication</span>
        <span class="it" style="display:none">Pubblicazione</span>
        <span class="ja" style="display:none">公開</span>
        <span class="zh-CN" style="display:none">发布</span>
        <span class="zh-TW" style="display:none">發佈</span>
    </h2>
    <ul>
      <li><a href="../../../guide/publishing/app-signing.html">
            <span class="en">Signing Your Applications</span>
            <span class="de" style="display:none">Signieren Ihrer Anwendungen</span>
            <span class="es" style="display:none">Firma de aplicaciones</span>
            <span class="fr" style="display:none">Attribution de votre signature <br />à vos applications</span>
            <span class="it" style="display:none">Firma delle applicazioni</span>
            <span class="ja" style="display:none">アプリケーションへの署名</span>
            <span class="zh-CN" style="display:none">应用程序签名</span>
            <span class="zh-TW" style="display:none">簽署應用程式</span>
          </a></li>
      <li><a href="../../../guide/publishing/versioning.html">
            <span class="en">Versioning Your Applications</span>
            <span class="de" style="display:none">Versionsverwaltung für Ihre <br />Anwendungen</span>
            <span class="es" style="display:none">Versiones de las aplicaciones</span>
            <span class="fr" style="display:none">Attribution d'une version à vos applications</span>
            <span class="it" style="display:none">Controllo versioni delle applicazioni</span>
            <span class="ja" style="display:none">アプリケーションのバージョニング</span>
            <span class="zh-CN" style="display:none">应用程序版本控制</span>
            <span class="zh-TW" style="display:none">應用程式版本設定</span>
          </a></li>
      <li><a href="../../../guide/publishing/preparing.html">
            <span class="en">Preparing to Publish</span>
            <span class="de" style="display:none">Vorbereitung auf die Veröffentlichung</span>
            <span class="es" style="display:none">Publicación de aplicaciones</span>
            <span class="fr" style="display:none">Préparation à la publication</span>
            <span class="it" style="display:none">Preparativi per la pubblicazione</span>
            <span class="ja" style="display:none">公開の準備</span>
            <span class="zh-CN" style="display:none">准备发布</span>
            <span class="zh-TW" style="display:none">準備發佈</span>
          </a></li>
      <li><a href="../../../guide/publishing/publishing.html">
            <span class="en">Publishing on Android Market</span>
          </a></li>
    </ul>
  </li>

  <li>
    <h2><span class="en">Best Practices</span>
               <span class="de" style="display:none">Bewährte Verfahren</span>
               <span class="es" style="display:none">Prácticas recomendadas</span>
               <span class="fr" style="display:none">Meilleures pratiques</span>
               <span class="it" style="display:none">Best practice</span>
               <span class="ja" style="display:none">ベスト プラクティス</span>
               <span class="zh-CN" style="display:none">最佳实践</span>
               <span class="zh-TW" style="display:none">最佳實務</span>
    </h2>
    <ul>
      <li><a href="../../../guide/practices/compatibility.html">
            <span class="en">Compatibility</span>
          </a></li>
      <li class="toggle-list">
        <div><a href="../../../guide/practices/screens_support.html">
          <span class="en">Supporting Multiple Screens</span>
        </a></div>
        <ul>
          <li><a href="../../../guide/practices/screens-distribution.html">
            <span class="en">Distributing to Specific Screens</span>
          </a></li>
          <li><a href="../../../guide/practices/screen-compat-mode.html">
            <span class="en">Screen Compatibility Mode</span>
          </a></li>
          <li><a href="../../../guide/practices/screens-support-1.5.html">
            <span class="en">Strategies for Android 1.5</span>
          </a></li>
        </ul>
      </li>
      <li><a href="../../../guide/practices/optimizing-for-3.0.html">
            <span class="en">Optimizing Apps for Android 3.0</span>
          </a></li>
      <li class="toggle-list">
        <div><a href="../../../guide/practices/ui_guidelines/index.html">
               <span class="en">UI Guidelines</span>
             </a></div>
        <ul>
          <li class="toggle-list">
            <div><a href="../../../guide/practices/ui_guidelines/icon_design.html">
                   <span class="en">Icon Design <span class="new">updated</span></span>
                 </a></div>
            <ul>
              <li><a href="../../../guide/practices/ui_guidelines/icon_design_launcher.html">
                    <span class="en">Launcher Icons <span class="new">updated</span></span>
                  </a></li>
              <li><a href="../../../guide/practices/ui_guidelines/icon_design_menu.html">
                    <span class="en">Menu Icons</span>
                  </a></li>
              <li><a href="../../../guide/practices/ui_guidelines/icon_design_action_bar.html">
                    <span class="en">Action Bar Icons <span class="new">new!</span></span>
                  </a></li>
              <li><a href="../../../guide/practices/ui_guidelines/icon_design_status_bar.html">
                    <span class="en">Status Bar Icons <span class="new">updated</span></span>
                  </a></li>
              <li><a href="../../../guide/practices/ui_guidelines/icon_design_tab.html">
                    <span class="en">Tab Icons</span>
                  </a></li>
              <li><a href="../../../guide/practices/ui_guidelines/icon_design_dialog.html">
                    <span class="en">Dialog Icons</span>
                  </a></li>
              <li><a href="../../../guide/practices/ui_guidelines/icon_design_list.html">
                    <span class="en">List View Icons</span>
                  </a></li>
            </ul>
          </li>
          <li><a href="../../../guide/practices/ui_guidelines/widget_design.html">
                <span class="en">App Widget Design <span class="new">updated</span></span>
              </a></li>
          <li><a href="../../../guide/practices/ui_guidelines/activity_task_design.html">
                <span class="en">Activity and Task Design</span>
              </a></li>
          <li><a href="../../../guide/practices/ui_guidelines/menu_design.html">
                <span class="en">Menu Design</span>
              </a></li>
        </ul>
      </li>
      </ul>
      <ul>
      <li><a href="../../../guide/practices/design/accessibility.html">
            <span class="en">Designing for Accessibility</span>
          </a></li>
      <li class="toggle-list">
        <div><a href="../../../guide/practices/design/performance.html">
            <span class="en">Designing for Performance</span>
          </a></div>
        <ul>
          <li><a href="../../../guide/practices/design/jni.html">
                <span class="en">JNI Tips</span>
              </a></li>
        </ul>
      </li>
      <li><a href="../../../guide/practices/design/responsiveness.html">
            <span class="en">Designing for Responsiveness</span>
          </a></li>
      <li><a href="../../../guide/practices/design/seamlessness.html">
            <span class="en">Designing for Seamlessness</span>
          </a></li>
    </ul>
  </li>

  <li>
    <h2><span class="en">Web Applications</span>
    </h2>
    <ul>
      <li><a href="../../../guide/webapps/index.html">
            <span class="en">Web Apps Overview</span>
          </a></li>
      <li><a href="../../../guide/webapps/targeting.html">
            <span class="en">Targeting Screens from Web Apps</span>
          </a></li>
      <li><a href="../../../guide/webapps/webview.html">
            <span class="en">Building Web Apps in WebView</span>
          </a></li>
      <li><a href="../../../guide/webapps/debugging.html">
            <span class="en">Debugging Web Apps</span>
          </a></li>
      <li><a href="../../../guide/webapps/best-practices.html">
            <span class="en">Best Practices for Web Apps</span>
          </a></li>
    </ul>
  </li>

  <li>
    <h2><span class="en">Appendix</span>
               <span class="de" style="display:none">Anhang</span>
               <span class="es" style="display:none">Apéndice</span>
               <span class="fr" style="display:none">Annexes</span>
               <span class="it" style="display:none">Appendice</span>
               <span class="ja" style="display:none">付録</span>
               <span class="zh-CN" style="display:none">附录</span>
               <span class="zh-TW" style="display:none">附錄</span>
    </h2>
    <ul>
      <li><a href="../../../guide/appendix/api-levels.html">
            <span class="en">Android API Levels</span>
          </a></li>
      <li><a href="../../../guide/appendix/install-location.html">
            <span class="en">App Install Location</span>
          </a></li>
      <li><a href="../../../guide/appendix/media-formats.html">
            <span class="en">Supported Media Formats <span class="new">updated</span></span>
          </a></li>
      <li><a href="../../../guide/appendix/g-app-intents.html">
            <span class="en">Intents List: Google Apps</span>
          </a></li>
      <li><a href="../../../guide/developing/tools/aidl.html">AIDL</a></li>
      <li><a href="../../../guide/appendix/glossary.html">
            <span class="en">Glossary</span>
          </a></li>
    </ul>
  </li>

</ul>

<script type="text/javascript">
<!--
    buildToggleLists();
    changeNavLang(getLangPref());
//-->
</script>

      </div>
    </div> <!-- end side-nav -->
    <script>
      addLoadEvent(function() {
        scrollIntoView("devdoc-nav");
        });
    </script>




<div class="g-unit" id="doc-content"><a name="top"></a>

<div id="jd-header" class="guide-header">
  <span class="crumb">
    
      <a href="index.html">In-app Billing</a> >
    
  </span>
<h1>Implementing In-app Billing</h1>
</div>

  <div id="jd-content">

    <div class="jd-descr">
    <div id="qv-wrapper">
<div id="qv">
  <h2>In this document</h2>
  <ol>
    <li><a href="#billing-download">Downloading the Sample Application</a></li>
    <li><a href="#billing-add-aidl">Adding the AIDL file to your project</a></li>
    <li><a href="#billing-permission">Updating Your Application's Manifest</a></li>
    <li><a href="#billing-service">Creating a Service</a></li>
    <li><a href="#billing-broadcast-receiver">Creating a BroadcastReceiver</a></li>
    <li><a href="#billing-signatures">Creating a security processing component</a></li>
    <li><a href="#billing-implement">Modifying Your Application Code</a></li>
  </ol>
  <h2>Downloads</h2>
  <ol>
    <li><a href="#billing-download">Sample Application</a></li>
  </ol>
  <h2>See also</h2>
  <ol>
    <li><a href="../../../guide/market/billing/billing_overview.html">Overview of In-app
    Billing</a></li>
    <li><a href="../../../guide/market/billing/billing_best_practices.html">Security and
    Design</a></li>
    <li><a href="../../../guide/market/billing/billing_testing.html">Testing In-app
    Billing</a></li>
    <li><a href="../../../guide/market/billing/billing_admin.html">Administering In-app
    Billing</a></li>
    <li><a href="../../../guide/market/billing/billing_reference.html">In-app Billing
    Reference</a></li>
  </ol>
</div>
</div>

<p>Android Market In-app Billing provides a straightforward, simple interface for sending in-app
billing requests and managing in-app billing transactions using Android Market. This document helps
you implement in-app billing by stepping through the primary implementation tasks, using the in-app
billing sample application as an example.</p>

<p>Before you implement in-app billing in your own application, be sure that you read <a
href="../../../guide/market/billing/billing_overview.html">Overview of In-app Billing</a> and <a
href="../../../guide/market/billing/billing_best_practices.html">Security and Design</a>. These
documents provide background information that will make it easier for you to implement in-app
billing.</p>

<p>To implement in-app billing in your application, you need to do the following:</p>
<ol>
  <li><a href="#billing-download">Download the in-app billing sample application</a>.</li>
  <li><a href="#billing-add-aidl">Add the IMarketBillingService.aidl file</a> to your project.</li>
  <li><a href="#billing-permission">Update your AndroidManifest.xml file</a>.</li>
  <li><a href="#billing-service">Create a Service</a> and bind it to the
  <code>MarketBillingService</code> so your application can send billing requests and receive
  billing responses from the Android Market application.</li>
  <li><a href="#billing-broadcast-receiver">Create a BroadcastReceiver</a> to handle broadcast
  intents from the Android Market application.</li>
  <li><a href="#billing-signatures">Create a security processing component</a> to verify the
  integrity of the transaction messages that are sent by Android Market .</li>
  <li><a href="#billing-implement">Modify your application code</a> to support in-app billing.</li>
</ol>

<h2 id="billing-download">Downloading the Sample Application</h2>

<p>The in-app billing sample application shows you how to perform several tasks that are common to
all Android Market in-app billing implementations, including:</p>

<ul>
  <li>Sending in-app billing requests to the Android Market application.</li>
  <li>Handling synchronous responses from the Android Market application.</li>
  <li>Handling broadcast intents (asynchronous responses) from the Android Market application.</li>
  <li>Using in-app billing security mechanisms to verify the integrity of billing responses.</li>
  <li>Creating a user interface that lets users select items for purchase.</li>
</ul>

<p>The sample application includes an application file (<code>Dungeons.java</code>), the AIDL file
for the <code>MarketBillingService</code> (<code>IMarketBillingService.aidl</code>), and several
classes that demonstrate in-app billing messaging. It also includes a class that demonstrates basic
security tasks, such as signature verification.</p>

<p>Table 1 lists the source files that are included with the sample application.</p>
<p class="table-caption" id="source-files-table"><strong>Table 1.</strong> In-app billing sample
application source files.</p>

<table>
<tr>
<th>File</th>
<th>Description</th>
</tr>

<tr>
<td>IMarketBillingService.aidl</td>
<td>Android Interface Definition Library (AIDL) file that defines the IPC interface to Android
Market's in-app billing service (<code>MarketBillingService</code>).</td>
</tr>

<tr>
<td>Dungeons.java</td>
<td>Sample application file that provides a UI for making purchases and displaying purchase
history.</td>
</tr>

<tr>
<td>PurchaseDatabase.java</td>
<td>A local database for storing purchase information.</td>
</tr>

<tr>
  <td>BillingReceiver.java</td>
  <td>A <code><a href="../../../reference/android/content/BroadcastReceiver.html">BroadcastReceiver</a></code> that receives asynchronous response messages
  (broadcast intents) from Android Market. Forwards all messages to the
  <code>BillingService</code>.</td>
</tr>
<tr>
  <td>BillingService.java</td>
  <td>A <code><a href="../../../reference/android/app/Service.html">Service</a></code> that sends messages to Android Market on behalf of the
  application by connecting (binding) to the <code>MarketBillingService</code>.</td>
</tr>

<tr>
  <td>ResponseHandler.java</td>
  <td>A <code><a href="../../../reference/android/os/Handler.html">Handler</a></code> that contains methods for updating the purchases database and the
  UI.</td>
</tr>

<tr>
  <td>PurchaseObserver.java</td>
  <td>An abstract class for observing changes related to purchases.</td>
</tr>

<tr>
<td>Security.java</td>
<td>Provides various security-related methods.</td>
</tr>

<tr>
<td>Consts.java</td>
<td>Defines various Android Market constants and sample application constants. All constants that
are defined by Android Market must be defined the same way in your application.</td>
</tr>

<tr>
<td>Base64.java and Base64DecoderException.java</td>
<td>Provides conversion services from binary to Base64 encoding. The <code>Security</code> class
relies on these utility classes.</td>
</tr>

</table>

<p>The in-app billing sample application is available as a downloadable component of the Android
SDK. To download the sample application component, launch the Android SDK and AVD Manager and then
select the "Google Market Billing package" component (see figure 1), and click <strong>Install
Selected</strong> to begin the download.</p>


<img src="../../../images/billing_package.png" height="325" id="figure1" />
<p class="img-caption">
  <strong>Figure 1.</strong> The Google Market Billing package contains the sample application and
  the AIDL file.
</p>

<p>When the download is complete, the Android SDK and AVD Manager saves the component into the
following directory:</p>

<p><code>&lt;sdk&gt;/extras/google/market_billing/</code></p>

<p>If you want to see an end-to-end demonstration of in-app billing before you integrate in-app
billing into your own application, you can build and run the sample application. Building and
running the sample application involves three tasks:</p>

<ul>
  <li>Configuring and building the sample application.</li>
  <li>Uploading the sample application to Android Market.</li>
  <li>Setting up test accounts and running the sample application.</li>
</ul>

<p class="note"><strong>Note:</strong> Building and running the sample application is necessary only
if you want to see a demonstration of in-app billing. If you do not want to run the sample
application, you can skip to the next section, <a href="#billing-add-aidl">Adding the AIDL file to
your project</a>.</p>

<h3>Configuring and building the sample application</h3>

<p>Before you can run the sample application, you need to configure it and build it by doing the
following:</p>

<ol>
  <li><strong>Add your Android Market public key to the sample application code.</strong>
    <p>This enables the application to verify the signature of the transaction information that is
    returned from Android Market. To add your public key to the sample application code, do the
    following:</p>
    <ol>
      <li>Log in to your Android Market <a href="http://market.android.com/publish">publisher
      account</a>.</li>
      <li>On the upper left part of the page, under your name, click <strong>Edit
      Profile</strong>.</li>
      <li>On the Edit Profile page, scroll down to the <strong>Licensing &amp; In-app
      Billing</strong> panel.</li>
      <li>Copy your public key.</li>
      <li>Open <code>src/com/example/dungeons/Security.java</code> in the editor of your choice.
        <p>You can find this file in the sample application's project folder.</p>
      </li>
      <li>Add your public key to the following line of code:
        <p><code>String base64EncodedPublicKey = "your public key here";</code></p>
      </li>
      <li>Save the file.</li>
    </ol>
  </li>
  <li><strong>Change the package name of the sample application.</strong>
    <p>The current package name is <code>com.example.dungeons</code>. Android Market does not let
    you upload applications with package names that contain <code>com.example</code>, so you must
    change the package name to something else.</p>
  </li>
  <li><strong>Build the sample application in release mode and sign it.</strong>
    <p>To learn how to build and sign applications, see <a
    href="../../../guide/developing/building/index.html">Building and Running</a>.</p>
  </li>
</ol>

<h3>Uploading the sample application</h3>

<p>After you build a release version of the sample application and sign it, you need to upload it as
a draft to the Android Market publisher site. You also need to create a product list for the in-app
items that are available for purchase in the sample application. The following instructions show you
how to do this.</p>
<ol>
  <li><strong>Upload the release version of the sample application to Android Market.</strong>
    <p>Do not publish the sample application; leave it as an unpublished draft application. The
    sample application is for demonstration purposes only and should not be made publicly available
    on Android Market. To learn how to upload an application to Android Market, see <a
    href="http://market.android.com/support/bin/answer.py?answer=113469">Uploading
    applications</a>.</p>
  </li>
  <li><strong>Create a product list for the sample application.</strong>
    <p>The sample application lets you purchase two items: a two-handed sword
    (<code>sword_001</code>) and a potion (<code>potion_001</code>). We recommend that you set up
    your product list so that <code>sword_001</code> has a purchase type of "Managed per user
    account" and <code>potion_001</code> has a purchase type of "Unmanaged" so you can see how these
    two purchase types behave. To learn how to set up a product list, see <a
    href="../../../guide/market/billing/billing_admin.html#billing-list-setup">Creating a Product
    List</a>.</p>
    <p class="note"><strong>Note:</strong> You must publish the items in your product
    list (<code>sword_001</code> and <code>potion_001</code>) even though you are not publishing the
    sample application. Also, you must have a Google Checkout Merchant account to add items to the
    sample application's product list.</p>
  </li>
</ol>

<h3>Running the sample application</h3>

<p>You cannot run the sample application in the emulator. You must install the sample application
onto a device to run it. To run the sample application, do the following:</p>

<ol>
  <li><strong>Make sure you have at least one test account registered under your Android Market
  publisher account.</strong>
    <p>You cannot purchase items from yourself (Google Checkout prohibits this), so you need to
    create at least one test account that you can use to purchase items in the sample application.
    To learn how to set up a test account, see <a
    href="../../../guide/market/billing/billing_testing.html#billing-testing-setup">Setting up Test
    Accounts</a>.</p>
  </li>
  <li><strong>Verify that your device is running a supported version of the Android Market
  application or the MyApps application.</strong>
    <p>If your device is running Android 3.0, in-app billing requires version 5.0.12 (or higher) of
    the MyApps application. If your device is running any other version of Android, in-app billing
    requires version 2.3.4 (or higher) of the Android Market application. To learn how to check the
    version of the Android Market application, see <a
    href="http://market.android.com/support/bin/answer.py?answer=190860">Updating Android
    Market</a>.</p>
  </li>
  <li><strong>Install the application onto your device.</strong>
    <p>Even though you uploaded the application to Android Market, the application is not published,
    so you cannot download it from Android Market to a device. Instead, you must install the
    application onto your device. To learn how to install an application onto a device, see <a
    href="../../../guide/developing/building/building-cmdline.html#RunningOnDevice">Running on a
    device</a>.</p>
 </li>
 <li><strong>Make one of your test accounts the primary account on your device.</strong>
    <p>The primary account on your device must be one of the <a
    href="../../../guide/market/billing/billing_admin.html#billing-testing-setup">test accounts</a>
    that you registered on the Android Market site. If the primary account on your device is not a
    test account, you must do a factory reset of the device and then sign in with one of your test
    accounts. To perform a factory reset, do the following:</p>
    <ol>
      <li>Open Settings on your device.</li>
      <li>Touch <strong>Privacy</strong>.</li>
      <li>Touch <strong>Factory data reset</strong>.</li>
      <li>Touch <strong>Reset phone</strong>.</li>
      <li>After the phone resets, be sure to sign in with one of your test accounts during the
      device setup process.</li>
    </ol>
  </li>
  <li><strong>Run the application and purchase the sword or the potion.</strong>
    <p>When you use a test account to purchase items, the test account is billed through Google
    Checkout and your Google Checkout Merchant account receives a payout for the purchase.
    Therefore, you may want to refund purchases that are made with test accounts, otherwise the
    purchases will show up as actual payouts to your merchant account.</p>
</ol>

<p class="note"><strong>Note</strong>: Debug log messages are turned off by default in the
sample application. You can turn them on by setting the variable <code>DEBUG</code>
to <code>true</code> in the <code>Consts.java</code> file.</p>

<h2 id="billing-add-aidl">Adding the AIDL file to your project</h2>

<p>The sample application contains an Android Interface Definition Language (AIDL) file,  which
defines the interface to Android Market's in-app billing service
(<code>MarketBillingService</code>). When you add this file to your project, the Android build
environment creates an interface file (<code>IMarketBillingService.java</code>). You can then use
this interface to make billing requests by invoking IPC method calls.</p>

<p>If you are using the ADT plug-in with Eclipse, you can just add this file to your
<code>/src</code> directory. Eclipse will automatically generate the interface file when you build
your project (which should happen immediately). If you are not using the ADT plug-in, you can put
the AIDL file into your project and use the Ant tool to build your project so that the
<code>IMarketBillingService.java</code> file gets generated.</p>

<p>To add the <code>IMarketBillingService.aidl</code> file to your project, do the following:</p>

<ol>
  <li>Create the following directory in your application's <code>/src</code> directory:
    <p><code>com/android/vending/billing/</code></p>
  </li>
  <li>Copy the <code>IMarketBillingService.aidl</code> file into the
  <code>sample/src/com/android/vending/billing/</code> directory.</li>
  <li>Build your application.</li>
</ol>

<p>You should now find a generated interface file named <code>IMarketBillingService.java</code> in
the <code>gen</code> folder of your project.</p>

<h2 id="billing-permission">Updating Your Application's Manifest</h2>

<p>In-app billing relies on the Android Market application, which handles all communication between
your application and the Android Market server. To use the Android Market application, your
application must request the proper permission. You can do this by adding the
<code>com.android.vending.BILLING</code> permission to your AndroidManifest.xml file. If your
application does not declare the in-app billing permission, but attempts to send billing requests,
Android Market will refuse the requests and respond with a <code>RESULT_DEVELOPER_ERROR</code>
response code.</p>

<p>In addition to the billing permission, you need to declare the <code><a href="../../../reference/android/content/BroadcastReceiver.html">BroadcastReceiver</a></code> that you will use to receive asynchronous response messages
(broadcast intents) from Android Market, and you need to declare the <code><a href="../../../reference/android/app/Service.html">Service</a></code>
that you will use to bind with the <code>IMarketBillingService</code> and send messages to Android
Market. You must also declare <a
href="../../../guide/topics/manifest/intent-filter-element.html">intent filters</a> for the <code><a href="../../../reference/android/content/BroadcastReceiver.html">BroadcastReceiver</a></code> so that the Android system knows how to handle the broadcast
intents that are sent from the Android Market application.</p>

<p>For example, here is how the in-app billing sample application declares the billing permission,
the <code><a href="../../../reference/android/content/BroadcastReceiver.html">BroadcastReceiver</a></code>, the <code><a href="../../../reference/android/app/Service.html">Service</a></code>, and the intent
filters. In the sample application, <code>BillingReceiver</code> is the <code><a href="../../../reference/android/content/BroadcastReceiver.html">BroadcastReceiver</a></code> that handles broadcast intents from the Android Market
application and <code>BillingService</code> is the <code><a href="../../../reference/android/app/Service.html">Service</a></code> that sends requests
to the Android Market application.</p>

<pre>
&lt;?xml version="1.0" encoding="utf-8"?&gt;
&lt;manifest xmlns:android="http://schemas.android.com/apk/res/android"
  package="com.example.dungeons"
  android:versionCode="1"
  android:versionName="1.0"&gt;

  &lt;uses-permission android:name="com.android.vending.BILLING" /&gt;

  &lt;application android:icon="@drawable/icon" android:label="@string/app_name"&gt;
    &lt;activity android:name=".Dungeons" android:label="@string/app_name"&gt;
      &lt;intent-filter&gt;
        &lt;action android:name="android.intent.action.MAIN" /&gt;
        &lt;category android:name="android.intent.category.LAUNCHER" /&gt;
      &lt;/intent-filter&gt;
    &lt;/activity&gt;

    &lt;service android:name="BillingService" /&gt;

    &lt;receiver android:name="BillingReceiver"&gt;
      &lt;intent-filter&gt;
        &lt;action android:name="com.android.vending.billing.IN_APP_NOTIFY" /&gt;
        &lt;action android:name="com.android.vending.billing.RESPONSE_CODE" /&gt;
        &lt;action android:name="com.android.vending.billing.PURCHASE_STATE_CHANGED" /&gt;
      &lt;/intent-filter&gt;
    &lt;/receiver&gt;

  &lt;/application&gt;
&lt;/manifest&gt;
</pre>

<h2 id="billing-service">Creating a Local Service</h2>

<p>Your application must have a local <code><a href="../../../reference/android/app/Service.html">Service</a></code> to facilitate messaging between
your application and Android Market. At a minimum, this service must do the following:</p>

<ul>
  <li>Bind to the <code>MarketBillingService</code>.
  <li>Send billing requests (as IPC method calls) to the Android Market application. The five types
  of billing requests include:
    <ul>
      <li><code>CHECK_BILLING_SUPPORTED</code> requests</li>
      <li><code>REQUEST_PURCHASE</code> requests</li>
      <li><code>GET_PURCHASE_INFORMATION</code> requests</li>
      <li><code>CONFIRM_NOTIFICATIONS</code> requests</li>
      <li><code>RESTORE_TRANSACTIONS</code> requests</li>
    </ul>
  </li>
  <li>Handle the synchronous response messages that are returned with each billing request.</li>
</ul>

<h3>Binding to the MarketBillingService</h3>

<p>Binding to the <code>MarketBillingService</code> is relatively easy if you've already added the
<code>IMarketBillingService.aidl</code> file to your project. The following code sample shows how to
use the <code><a href="../../../reference/android/content/Context.html#bindService(android.content.Intent, android.content.ServiceConnection, int)">bindService()</a></code> method to bind a service to the
<code>MarketBillingService</code>. You could put this code in your service's <code><a href="../../../reference/android/app/Activity.html#onCreate(android.os.Bundle)">onCreate()</a></code> method.</p>

<pre>
try {
  boolean bindResult = mContext.bindService(
    new Intent("com.android.vending.billing.MarketBillingService.BIND"), this,
    Context.BIND_AUTO_CREATE);
  if (bindResult) {
    Log.i(TAG, "Service bind successful.");
  } else {
    Log.e(TAG, "Could not bind to the MarketBillingService.");
  }
} catch (SecurityException e) {
  Log.e(TAG, "Security exception: " + e);
}
</pre>

<p>After you bind to the service, you need to create a reference to the
<code>IMarketBillingService</code> interface so you can make billing requests via IPC method calls.
The following code shows you how to do this using the <code><a href="../../../reference/android/content/ServiceConnection.html#onServiceConnected(android.content.ComponentName, android.os.IBinder)">onServiceConnected()</a></code> callback method.</p>

<pre>
/**
  * The Android system calls this when we are connected to the MarketBillingService.
  */
  public void onServiceConnected(ComponentName name, IBinder service) {
    Log.i(TAG, "MarketBillingService connected.");
    mService = IMarketBillingService.Stub.asInterface(service);
  }
</pre>

<p>You can now use the <code>mService</code> reference to invoke the
<code>sendBillingRequest()</code> method.</p>

<p>For a complete implementation of a service that binds to the <code>MarketBillingService</code>,
see the <code>BillingService</code> class in the sample application.</p>

<h3>Sending billing requests to the MarketBillingService</h3>

<p>Now that your <code><a href="../../../reference/android/app/Service.html">Service</a></code> has a reference to the
<code>IMarketBillingService</code> interface, you can use that reference to send billing requests
(via IPC method calls) to the <code>MarketBillingService</code>. The
<code>MarketBillingService</code> IPC interface exposes a single public method
(<code>sendBillingRequest()</code>), which takes a single <code><a href="../../../reference/android/os/Bundle.html">Bundle</a></code> parameter. The
Bundle that you deliver with this method specifies the type of request you want to perform, using
various key-value pairs. For instance, one key indicates the type of request you are making, another
indicates the item being purchased, and another identifies your application. The
<code>sendBillingRequest()</code> method immediately returns a Bundle containing an initial response
code. However, this is not the complete purchase response; the complete response is delivered with
an asynchronous broadcast intent. For more information about the various Bundle keys that are
supported by the <code>MarketBillingService</code>, see <a
href="../../../guide/market/billing/billing_reference.html#billing-interface">In-app Billing
Service Interface</a>.</p>

<p>You can use the <code>sendBillingRequest()</code> method to send five types of billing requests.
The five request types are specified using the <code>BILLING_REQUEST</code> Bundle key. This Bundle
key can have the following five values:</p>

<ul>
  <li><code>CHECK_BILLING_SUPPORTED</code>&mdash;verifies that the Android Market application
  supports in-app billing.</li>
  <li><code>REQUEST_PURCHASE</code>&mdash;sends a purchase request for an in-app item.</li> 
  <li><code>GET_PURCHASE_INFORMATION</code>&mdash;retrieves transaction information for a purchase
  or refund.</li>
  <li><code>CONFIRM_NOTIFICATIONS</code>&mdash;acknowledges that you received the transaction
  information for a purchase or refund.</li>
  <li><code>RESTORE_TRANSACTIONS</code>&mdash;retrieves a user's transaction history for <a
  href="../../../guide/market/billing/billing_admin.html#billing-purchase-type">managed
  purchases</a>.</li>
</ul>

<p>To make any of these billing requests, you first need to build an initial <code><a href="../../../reference/android/os/Bundle.html">Bundle</a></code> that contains the three keys that are required for all requests:
<code>BILLING_REQUEST</code>, <code>API_VERSION</code>, and <code>PACKAGE_NAME</code>. The following
code sample shows you how to create a helper method named <code>makeRequestBundle()</code> that does
this.</p>

<pre>
protected Bundle makeRequestBundle(String method) {
  Bundle request = new Bundle();
  request.putString(BILLING_REQUEST, method);
  request.putInt(API_VERSION, 1);
  request.putString(PACKAGE_NAME, getPackageName());
  return request;
</pre>

<p>To use this helper method, you pass in a <code>String</code> that corresponds to one of the five
types of billing requests. The method returns a Bundle that has the three required keys defined. The
following sections show you how to use this helper method when you send a billing request.</p>

<p class="caution"><strong>Important</strong>: You must make all in-app billing requests from your
application's main thread.</p>

<h4>Verifying that in-app billing is supported (CHECK_BILLING_SUPPPORTED)</h4>

<p>The following code sample shows how to verify whether the Android Market application supports
in-app billing. In the sample, <code>mService</code> is an instance of the
<code>MarketBillingService</code> interface.</p>

<pre>
/**
* Request type is CHECK_BILLING_SUPPORTED
*/
  Bundle request = makeRequestBundle("CHECK_BILLING_SUPPORTED");
  Bundle response = mService.sendBillingRequest(request);
  // Do something with this response.
}
</pre>
<p>The <code>makeRequestBundle()</code> method constructs an initial Bundle, which contains the
three keys that are required for all requests: <code>BILLING_REQUEST</code>,
<code>API_VERSION</code>, and <code>PACKAGE_NAME</code>. The request returns a synchronous <code><a href="../../../reference/android/os/Bundle.html">Bundle</a></code> response, which contains only a single key: <code>RESPONSE_CODE</code>. The
<code>RESPONSE_CODE</code> key can have the following values:</p>
<ul>
  <li><code>RESULT_OK</code>&mdash;in-app billing is supported.</li>
  <li><code>RESULT_BILLING_UNAVAILABLE</code>&mdash;in-app billing is not available because the API
  version you specified is not recognized or the user is not eligible to make in-app purchases (for
  example, the user resides in a country that prohibits in-app purchases).</li>
  <li><code>RESULT_ERROR</code>&mdash;there was an error connecting with the Android Market
  application.</li>
  <li><code>RESULT_DEVELOPER_ERROR</code>&mdash;the application is trying to make an in-app billing
  request but the application has not declared the <code>com.android.vending.BILLING</code>
  permission in its manifest. Can also indicate that an application is not properly signed, or that
  you sent a malformed request.</li>
</ul>

<p>The <code>CHECK_BILLING_SUPPORTED</code> request does not trigger any asynchronous responses
(broadcast intents).</p>

<p>We recommend that you invoke the <code>CHECK_BILLING_SUPPORTED</code> request within a
<code>RemoteException</code> block. When your code throws a <code>RemoteException</code> it
indicates that the remote method call failed, which means that the Android Market application is out
of date and needs to be updated. In this case, you can provide users with an error message that
contains a link to the <a
href="http://market.android.com/support/bin/answer.py?answer=190860">Updating Android Market</a>
Help topic.</p>

<p>The sample application demonstrates how you can handle this error condition (see
<code>DIALOG_CANNOT_CONNECT_ID</code> in <code>Dungeons.java</code>).</p>

<h4>Making a purchase request (REQUEST_PURCHASE)</h4>

<p>To make a purchase request you must do the following:</p>

<ul>
  <li>Send the <code>REQUEST_PURCHASE</code> request.</li>
  <li>Launch the <code><a href="../../../reference/android/app/PendingIntent.html">PendingIntent</a></code> that is returned from the Android Market
  application.</li>
  <li>Handle the broadcast intents that are sent by the Android Market application.</li>
</ul>

<h5>Making the request</h5>

<p>You must specify four keys in the request <code><a href="../../../reference/android/os/Bundle.html">Bundle</a></code>. The following code sample
shows how to set these keys and make a purchase request for a single in-app item. In the sample,
<code>mProductId</code> is the Android Market product ID of an in-app item (which is listed in the
application's <a href="../../../guide/market/billing/billing_admin.html#billing-list-setup">product
list</a>), and <code>mService</code> is an instance of the <code>MarketBillingService</code>
interface.</p>

<pre>
/**
* Request type is REQUEST_PURCHASE
*/
  Bundle request = makeRequestBundle("REQUEST_PURCHASE");
  request.putString(ITEM_ID, mProductId);
  // Note that the developer payload is optional.
  if (mDeveloperPayload != null) {
    request.putString(DEVELOPER_PAYLOAD, mDeveloperPayload);
  Bundle response = mService.sendBillingRequest(request);
  // Do something with this response.
  }
</pre>
<p>The <code>makeRequestBundle()</code> method constructs an initial Bundle, which contains the
three keys that are required for all requests: <code>BILLING_REQUEST</code>,
<code>API_VERSION</code>, and <code>PACKAGE_NAME</code>. The <code>ITEM_ID</code> key is then added
to the Bundle prior to invoking the <code>sendBillingRequest()</code> method.</p>

<p>The request returns a synchronous <code><a href="../../../reference/android/os/Bundle.html">Bundle</a></code> response, which contains three keys:
<code>RESPONSE_CODE</code>, <code>PURCHASE_INTENT</code>, and <code>REQUEST_ID</code>. The
<code>RESPONSE_CODE</code> key provides you with the status of the request and the
<code>REQUEST_ID</code> key provides you with a unique request identifier for the request. The
<code>PURCHASE_INTENT</code> key provides you with a <code><a href="../../../reference/android/app/PendingIntent.html">PendingIntent</a></code>, which you
can use to launch the checkout UI.</p>

<h5>Using the pending intent</h5>

<p>How you use the pending intent depends on which version of Android a device is running. On
Android 1.6, you must use the pending intent to launch the checkout UI in its own separate task
instead of your application's activity stack. On Android 2.0 and higher, you can use the pending
intent to launch the checkout UI on your application's activity stack. The following code shows you
how to do this. You can find this code in the <code>PurchaseObserver.java</code> file in the sample
application.</p>

<pre>
void startBuyPageActivity(PendingIntent pendingIntent, Intent intent) {
  if (mStartIntentSender != null) {
    // This is on Android 2.0 and beyond.  The in-app checkout page activity
    // will be on the activity stack of the application.
    try {
      // This implements the method call:
      // mActivity.startIntentSender(pendingIntent.getIntentSender(),
      //     intent, 0, 0, 0);
      mStartIntentSenderArgs[0] = pendingIntent.getIntentSender();
      mStartIntentSenderArgs[1] = intent;
      mStartIntentSenderArgs[2] = Integer.valueOf(0);
      mStartIntentSenderArgs[3] = Integer.valueOf(0);
      mStartIntentSenderArgs[4] = Integer.valueOf(0);
      mStartIntentSender.invoke(mActivity, mStartIntentSenderArgs);
    } catch (Exception e) {
      Log.e(TAG, "error starting activity", e);
      }
  } else {
    // This is on Android 1.6. The in-app checkout page activity will be on its
    // own separate activity stack instead of on the activity stack of
    // the application.
    try {
      pendingIntent.send(mActivity, 0 /* code */, intent);
    } catch (CanceledException e) {
      Log.e(TAG, "error starting activity", e);
      }
  }
}
</pre>

<p class="caution"><strong>Important:</strong> You must launch the pending intent from an activity
context and not an application context. Also, you cannot use the <code>singleTop</code> <a
href="../../../guide/topics/manifest/activity-element.html#lmode">launch mode</a> to launch the
pending intent. If you do either of these, the Android system will not attach the pending intent to
your application process. Instead, it will bring Android Market to the foreground, disrupting your
application.</p>

<h5>Handling broadcast intents</h5>

<p>A <code>REQUEST_PURCHASE</code> request also triggers two asynchronous responses (broadcast
intents). First, the Android Market application sends a <code>RESPONSE_CODE</code> broadcast intent,
which provides error information about the request. If the request does not generate an
error, the <code>RESPONSE_CODE</code> broadcast intent returns <code>RESULT_OK</code>, which
indicates that the request was successfully sent. (To be clear, a <code>RESULT_OK</code> response
does not indicate that the requested purchase was successful; it indicates that the request was sent
successfully to Android Market.)</p>

<p>Next, when the requested transaction changes state (for example, the purchase is successfully
charged to a credit card or the user cancels the purchase), the Android Market application sends an
<code>IN_APP_NOTIFY</code> broadcast intent. This message contains a notification ID, which you can
use to retrieve the transaction details for the <code>REQUEST_PURCHASE</code> request.</p>

<p class="note"><strong>Note:</strong> The Android Market application also sends
an <code>IN_APP_NOTIFY</code> for refunds. For more information, see <a
href="../../../guide/market/billing/billing_overview.html#billing-action-notify">Handling
IN_APP_NOTIFY messages</a>.</p>

<p>Because the purchase process is not instantaneous and can take several seconds (or more), you
must assume that a purchase request is pending from the time you receive a <code>RESULT_OK</code>
message until you receive an <code>IN_APP_NOTIFY</code> message for the transaction. While the
transaction is pending, the Android Market checkout UI displays an "Authorizing purchase..."
notification; however, this notification is dismissed after 60 seconds and you should not rely on
this notification as your primary means of conveying transaction status to users. Instead, we
recommend that you do the following:</p>

<ul>
  <li>Add an <code><a href="../../../reference/android/app/Activity.html">Activity</a></code> to your application that shows users the status of pending
and completed in-app purchases.</li>
  <li>Use a <a href="../../../guide/topics/ui/notifiers/notifications.html">status
bar notification</a> to keep users informed about the progress of a purchase.</li>
</ul>

<p>To use these two UI elements, you could invoke a status bar notification with a ticker-text
message that says "Purchase pending" when your application receives a <code>RESULT_OK</code>
message. Then, when your application receives an <code>IN_APP_NOTIFY</code> message, you could
update the notification with a new message that says "Purchase succeeded" or "Purchase failed." When
a user touches the expanded status bar notification, you could launch the activity that shows the
status of pending and completed in-app purchases.</p>

<p>If you use some other UI technique to inform users about the state of a pending transaction,
be sure that your pending status UI does not block your application. For example, you should avoid
using a hovering progress wheel to convey the status of a pending transaction because a pending
transaction could last a long time, particularly if a device loses network connectivity and cannot
receive transaction updates from Android Market.</p>

<p class="caution"><strong>Important:</strong> If a user purchases a managed item, you must prevent
the user from purchasing the item again while the original transaction is pending. If a user
attempts to purchase a managed item twice, and the first transaction is still pending, Android
Market will display an error to the user; however, Android Market will not send an error to your
application notifying you that the second purchase request was canceled. This might cause your
application to get stuck in a pending state while it waits for an <code>IN_APP_NOTIFY</code> message
for the second purchase request.</p>

<h4>Retrieving transaction information for a purchase or refund (GET_PURCHASE_INFORMATION)</h4>

<p>You retrieve transaction information in response to an <code>IN_APP_NOTIFY</code> broadcast
intent. The <code>IN_APP_NOTIFY</code> message contains a notification ID, which you can use to
retrieve transaction information.</p>

<p>To retrieve transaction information for a purchase or refund you must specify five keys in the
request <code><a href="../../../reference/android/os/Bundle.html">Bundle</a></code>. The following code sample shows how to set these keys and make
the request. In the sample, <code>mService</code> is an instance of the
<code>MarketBillingService</code> interface.</p>

<pre>
/**
* Request type is GET_PURCHASE_INFORMATION
*/
  Bundle request = makeRequestBundle("GET_PURCHASE_INFORMATION");
  request.putLong(REQUEST_NONCE, mNonce);
  request.putStringArray(NOTIFY_IDS, mNotifyIds);
  Bundle response = mService.sendBillingRequest(request);
  // Do something with this response.
}
</pre>
<p>The <code>makeRequestBundle()</code> method constructs an initial Bundle, which contains the
three keys that are required for all requests: <code>BILLING_REQUEST</code>,
<code>API_VERSION</code>, and <code>PACKAGE_NAME</code>. The additional keys are then added to the
bundle prior to invoking the <code>sendBillingRequest()</code> method. The
<code>REQUEST_NONCE</code> key contains a cryptographically secure nonce (number used once) that you
must generate. The Android Market application returns this nonce with the
<code>PURCHASE_STATE_CHANGED</code> broadcast intent so you can verify the integrity of the
transaction information. The <code>NOTIFY_IDS</code> key contains an array of notification IDs,
which you received in the <code>IN_APP_NOTIFY</code> broadcast intent.</p>

<p>The request returns a synchronous <code><a href="../../../reference/android/os/Bundle.html">Bundle</a></code> response, which contains two keys:
<code>RESPONSE_CODE</code> and <code>REQUEST_ID</code>. The <code>RESPONSE_CODE</code> key provides
you with the status of the request and the <code>REQUEST_ID</code> key provides you with a unique
request identifier for the request.</p>

<p>A <code>GET_PURCHASE_INFORMATION</code> request also triggers two asynchronous responses
(broadcast intents). First, the Android Market application sends a <code>RESPONSE_CODE</code>
broadcast intent, which provides status and error information about the request. Next, if the
request was successful, the Android Market application sends a <code>PURCHASE_STATE_CHANGED</code>
broadcast intent. This message contains detailed transaction information. The transaction
information is contained in a signed JSON string (unencrypted). The message includes the signature
so you can verify the integrity of the signed string.</p>

<h4>Acknowledging transaction information (CONFIRM_NOTIFICATIONS)</h4>

<p>To acknowledge that you received transaction information you send a
<code>CONFIRM_NOTIFICATIONS</code> request. You must specify four keys in the request <code><a href="../../../reference/android/os/Bundle.html">Bundle</a></code>. The following code sample shows how to set these keys and make the request. In
the sample, <code>mService</code> is an instance of the <code>MarketBillingService</code>
interface.</p>

<pre>
/**
* Request type is CONFIRM_NOTIFICATIONS
*/
  Bundle request = makeRequestBundle("CONFIRM_NOTIFICATIONS");
  request.putStringArray(NOTIFY_IDS, mNotifyIds);
  Bundle response = mService.sendBillingRequest(request);
  // Do something with this response.
}
</pre>
<p>The <code>makeRequestBundle()</code> method constructs an initial Bundle, which contains the
three keys that are required for all requests: <code>BILLING_REQUEST</code>,
<code>API_VERSION</code>, and <code>PACKAGE_NAME</code>. The additional <code>NOTIFY_IDS</code> key
is then added to the bundle prior to invoking the <code>sendBillingRequest()</code> method. The
<code>NOTIFY_IDS</code> key contains an array of notification IDs, which you received in an
<code>IN_APP_NOTIFY</code> broadcast intent and also used in a <code>GET_PURCHASE_INFORMATION</code>
request.</p>

<p>The request returns a synchronous <code><a href="../../../reference/android/os/Bundle.html">Bundle</a></code> response, which contains two keys:
<code>RESPONSE_CODE</code> and <code>REQUEST_ID</code>. The <code>RESPONSE_CODE</code> key provides
you with the status of the request and the <code>REQUEST_ID</code> key provides you with a unique
request identifier for the request.</p>

<p>A <code>CONFIRM_NOTIFICATIONS</code> request triggers a single asynchronous response&mdash;a
<code>RESPONSE_CODE</code> broadcast intent. This broadcast intent provides status and error
information about the request.</p>

<p>You must send a confirmation when you receive transaction information from Android Market. If you
don't send a confirmation message, Android Market will continue sending
<code>IN_APP_NOTIFY</code> messages for the transactions you have not confirmed. Also,
your application must be able to handle <code>IN_APP_NOTIFY</code> messages that contain multiple
orders.</p>

<p>In addition, as a best practice, you should not send a <code>CONFIRM_NOTIFICATIONS</code> request
for a purchased item until you have delivered the item to the user. This way, if your application
crashes or something else prevents your application from delivering the product, your application
will still receive an <code>IN_APP_NOTIFY</code> broadcast intent from Android Market indicating
that you need to deliver the product.</p>

<h4>Restoring transaction information (RESTORE_TRANSACTIONS)</h4>

<p>To restore a user's transaction information, you send a <code>RESTORE_TRANSACTIONS</code>
request. You must specify four keys in the request <code><a href="../../../reference/android/os/Bundle.html">Bundle</a></code>. The following code
sample shows how to set these keys and make the request. In the sample, <code>mService</code> is an
instance of the <code>MarketBillingService</code> interface.</p>

<pre>
/**
* Request type is RESTORE_TRANSACTIONS
*/
  Bundle request = makeRequestBundle("RESTORE_TRANSACTIONS");
  request.putLong(REQUEST_NONCE, mNonce);
  Bundle response = mService.sendBillingRequest(request);
  // Do something with this response.
}
</pre>
<p>The <code>makeRequestBundle()</code> method constructs an initial Bundle, which contains the
three keys that are required for all requests: <code>BILLING_REQUEST</code>,
<code>API_VERSION</code>, and <code>PACKAGE_NAME</code>. The additional <code>REQUEST_NONCE</code>
key is then added to the bundle prior to invoking the <code>sendBillingRequest()</code> method. The
<code>REQUEST_NONCE</code> key contains a cryptographically secure nonce (number used once) that you
must generate. The Android Market application returns this nonce with the transactions information
contained in the <code>PURCHASE_STATE_CHANGED</code> broadcast intent so you can verify the
integrity of the transaction information.</p>

<p>The request returns a synchronous <code><a href="../../../reference/android/os/Bundle.html">Bundle</a></code> response, which contains two keys:
<code>RESPONSE_CODE</code> and <code>REQUEST_ID</code>. The <code>RESPONSE_CODE</code> key provides
you with the status of the request and the <code>REQUEST_ID</code> key provides you with a unique
request identifier for the request.</p>

<p>A <code>RESTORE_TRANSACTIONS</code> request also triggers two asynchronous responses (broadcast
intents). First, the Android Market application sends a <code>RESPONSE_CODE</code> broadcast intent,
which provides status and error information about the request. Next, if the request was successful,
the Android Market application sends a <code>PURCHASE_STATE_CHANGED</code> broadcast intent. This
message contains the detailed transaction information. The transaction information is contained in a
signed JSON string (unencrypted). The message includes the signature so you can verify the integrity
of the signed string.</p>

<p class="note"><strong>Note:</strong> You should use the <code>RESTORE_TRANSACTIONS</code>
request type only when your application is installed for the first time on a device or when your
application has been removed from a device and reinstalled.</p>

<h3>Other service tasks</h3>

<p>You may also want your <code><a href="../../../reference/android/app/Service.html">Service</a></code> to receive intent messages from your <code><a href="../../../reference/android/content/BroadcastReceiver.html">BroadcastReceiver</a></code>. You can use these intent messages to convey the information that
was sent asynchronously from the Android Market application to your <code><a href="../../../reference/android/content/BroadcastReceiver.html">BroadcastReceiver</a></code>. To see an example of how you can send and receive these intent
messages, see the <code>BillingReceiver.java</code> and <code>BillingService.java</code> files in
the sample application. You can use these samples as a basis for your own implementation. However,
if you use any of the code from the sample application, be sure you follow the guidelines in <a
href="../../../guide/market/billing/billing_best_practices.html">Security and Design</a>.</p>

<h2 id="billing-broadcast-receiver">Creating a BroadcastReceiver</h2>

<p>The Android Market application uses broadcast intents to send asynchronous billing responses to
your application. To receive these intent messages, you need to create a <code><a href="../../../reference/android/content/BroadcastReceiver.html">BroadcastReceiver</a></code> that can handle the following intents:</p>

<ul>
  <li>com.android.vending.billing.RESPONSE_CODE
  <p>This broadcast intent contains an Android Market response code, and is sent after you make an
  in-app billing request. For more information about the response codes that are sent with this
  response, see <a
  href="../../../guide/market/billing/billing_reference.html#billing-codes">Android Market Response
  Codes for In-app Billing</a>.</p>
  </li>
  <li>com.android.vending.billing.IN_APP_NOTIFY
  <p>This response indicates that a purchase has changed state, which means a purchase succeeded,
  was canceled, or was refunded. For more information about notification messages, see <a
  href="../../../guide/market/billing/billing_reference.html#billing-intents">In-app Billing
  Broadcast Intents</a></p>
  </li>
  <li>com.android.vending.billing.PURCHASE_STATE_CHANGED
  <p>This broadcast intent contains detailed information about one or more transactions. For more
  information about purchase state messages, see <a
  href="../../../guide/market/billing/billing_reference.html#billing-intents">In-app Billing
  Broadcast Intents</a></p>
  </li>
</ul>

<p>Each of these broadcast intents provide intent extras, which your <code><a href="../../../reference/android/content/BroadcastReceiver.html">BroadcastReceiver</a></code> must handle. The intent extras are listed in the following table
(see table 1).</p>

<p class="table-caption"><strong>Table 1.</strong> Description of broadcast intent extras that are
sent in response to billing requests.</p>

<table>

<tr>
<th>Intent</th>
<th>Extra</th>
<th>Description</th>
</tr>
<tr>
  <td><code>com.android.vending.billing.RESPONSE_CODE</code></td>
  <td><code>request_id</code></td>
  <td>A <code>long</code> representing a request ID. A request ID identifies a specific billing
  request and is returned by Android Market at the time a request is made.</td>
</tr>
<tr>
  <td><code>com.android.vending.billing.RESPONSE_CODE</code></td>
  <td><code>response_code</code></td>
  <td>An <code>int</code> representing the actual Android Market server response code.</td>
</tr>
<tr>
  <td><code>com.android.vending.billing.IN_APP_NOTIFY</code></td>
  <td><code>notification_id</code></td>
  <td>A <code>String</code> representing the notification ID for a given purchase state change.
  Android Market notifies you when there is a purchase state change and the notification includes a
  unique notification ID. To get the details of the purchase state change, you send the notification
  ID with the <code>GET_PURCHASE_INFORMATION</code> request.</td>
</tr>
<tr>
  <td><code>com.android.vending.billing.PURCHASE_STATE_CHANGED</code></td>
  <td><code>inapp_signed_data</code></td>
  <td>A <code>String</code> representing the signed JSON string. The JSON string contains
  information about the billing transaction, such as order number, amount, and the item that was
  purchased or refunded.</td>
</tr>
<tr>
  <td><code>com.android.vending.billing.PURCHASE_STATE_CHANGED</code></td>
  <td><code>inapp_signature</code></td>
  <td>A <code>String</code> representing the signature of the JSON string.</td>
</tr>
</table>

<p>The following code sample shows how to handle these broadcast intents and intent extras within a
<code><a href="../../../reference/android/content/BroadcastReceiver.html">BroadcastReceiver</a></code>. The BroadcastReceiver in this case is named
<code>BillingReceiver</code>, just as it is in the sample application.</p>

<pre>
public class BillingReceiver extends BroadcastReceiver {
  
  private static final String TAG = "BillingReceiver";
  
  // Intent actions that we receive in the BillingReceiver from Android Market.
  // These are defined by Android Market and cannot be changed.
  // The sample application defines these in the Consts.java file.
  public static final String ACTION_NOTIFY = "com.android.vending.billing.IN_APP_NOTIFY";
  public static final String ACTION_RESPONSE_CODE = "com.android.vending.billing.RESPONSE_CODE";
  public static final String ACTION_PURCHASE_STATE_CHANGED =
    "com.android.vending.billing.PURCHASE_STATE_CHANGED";
    
  // The intent extras that are passed in an intent from Android Market.
  // These are defined by Android Market and cannot be changed.
  // The sample application defines these in the Consts.java file.
  public static final String NOTIFICATION_ID = "notification_id";
  public static final String INAPP_SIGNED_DATA = "inapp_signed_data";
  public static final String INAPP_SIGNATURE = "inapp_signature";
  public static final String INAPP_REQUEST_ID = "request_id";
  public static final String INAPP_RESPONSE_CODE = "response_code";


  &#64;Override
  public void onReceive(Context context, Intent intent) {
    String action = intent.getAction();
    if (ACTION_PURCHASE_STATE_CHANGED.equals(action)) {
      String signedData = intent.getStringExtra(INAPP_SIGNED_DATA);
      String signature = intent.getStringExtra(INAPP_SIGNATURE);
      // Do something with the signedData and the signature.
    } else if (ACTION_NOTIFY.equals(action)) {
      String notifyId = intent.getStringExtra(NOTIFICATION_ID);
      // Do something with the notifyId.
    } else if (ACTION_RESPONSE_CODE.equals(action)) {
      long requestId = intent.getLongExtra(INAPP_REQUEST_ID, -1);
      int responseCodeIndex = intent.getIntExtra(INAPP_RESPONSE_CODE,
        ResponseCode.RESULT_ERROR.ordinal());
      // Do something with the requestId and the responseCodeIndex.
    } else {
      Log.w(TAG, "unexpected action: " + action);
    }
  }
  // Perform other processing here, such as forwarding intent messages to your local service.
}
</pre>

<p>In addition to receiving broadcast intents from the Android Market application, your <code><a href="../../../reference/android/content/BroadcastReceiver.html">BroadcastReceiver</a></code> must handle the information it received in the broadcast intents.
Usually, your <code><a href="../../../reference/android/content/BroadcastReceiver.html">BroadcastReceiver</a></code> does this by sending the information to a
local service (discussed in the next section). The <code>BillingReceiver.java</code> file in the
sample application shows you how to do this. You can use this sample as a basis for your own <code><a href="../../../reference/android/content/BroadcastReceiver.html">BroadcastReceiver</a></code>. However, if you use any of the code from the sample application,
be sure you follow the guidelines that are discussed in <a
href="../../../guide/market/billing/billing_best_practices.html">Security and Design </a>.</p>

<h2 id="billing-signatures">Verifying Signatures and Nonces</h2>

<p>Android Market's in-app billing service uses two mechanisms to help verify the integrity of the
transaction information you receive from Android Market: nonces and signatures. A nonce (number used
once) is a cryptographically secure number that your application generates and sends with every
<code>GET_PURCHASE_INFORMATION</code> and <code>RESTORE_TRANSACTIONS</code> request. The nonce is
returned with the <code>PURCHASE_STATE_CHANGED</code> broadcast intent, enabling you to verify that
any given <code>PURCHASE_STATE_CHANGED</code> response corresponds to an actual request that you
made. Every <code>PURCHASE_STATE_CHANGED</code> broadcast intent also includes a signed JSON string
and a signature, which you can use to verify the integrity of the response.</p>

<p>Your application must provide a way to generate, manage, and verify nonces. The following sample
code shows some simple methods you can use to do this.</p>

<pre>
  private static final SecureRandom RANDOM = new SecureRandom();
  private static HashSet&lt;Long&gt; sKnownNonces = new HashSet&lt;Long&gt;();

  public static long generateNonce() {
    long nonce = RANDOM.nextLong();
    sKnownNonces.add(nonce);
    return nonce;
  }

  public static void removeNonce(long nonce) {
    sKnownNonces.remove(nonce);
  }

  public static boolean isNonceKnown(long nonce) {
    return sKnownNonces.contains(nonce);
  }
</pre>

<p>Your application must also provide a way to verify the signatures that accompany every
<code>PURCHASE_STATE_CHANGED</code> broadcast intent. The <code>Security.java</code> file in the
sample application shows you how to do this. If you use this file as a basis for your own security
implementation, be sure to follow the guidelines in <a
href="../../../guide/market/billing/billing_best_practices.html">Security and Design</a> and
obfuscate your code.</p>

<p>You will need to use your Android Market public key to perform the signature verification. The
following procedure shows you how to retrieve Base64-encoded public key from the Android Market
publisher site.</p>

<ol>
  <li>Log in to your <a href="http://market.android.com/publish">publisher account</a>.</li>
  <li>On the upper left part of the page, under your name, click <strong>Edit profile</strong>.</li>
  <li>On the Edit Profile page, scroll down to the Licensing &amp; In-app Billing panel (see figure
  2).</li>
  <li>Copy your public key.</li>
</ol>

<p class="caution"><strong>Important</strong>: To keep your public key safe from malicious users and
hackers, do not embed your public key as an entire literal string. Instead, construct the string at
runtime from pieces or use bit manipulation (for example, XOR with some other string) to hide the
actual key. The key itself is not secret information, but you do not want to make it easy for a
hacker or malicious user to replace the public key with another key.</p>

<img src="../../../images/billing_public_key.png" height="510" id="figure2" />
<p class="img-caption">
  <strong>Figure 2.</strong> The Licensing and In-app Billing panel of your account's Edit Profile
  page lets you see your public key.
</p>

<h2 id="billing-implement">Modifying Your Application Code</h2>

<p>After you finish adding in-app billing components to your project, you are ready to modify your
application's code. For a typical implementation, like the one that is demonstrated in the sample
application, this means you need to write code to do the following: </p>

<ul>
  <li>Create a storage mechanism for storing users' purchase information.</li>
  <li>Create a user interface that lets users select items for purchase.</li>
</ul>

<p>The sample code in <code>Dungeons.java</code> shows you how to do both of these tasks.</p>

<h3>Creating a storage mechanism for storing purchase information</h3>

<p>You must set up a database or some other mechanism for storing users' purchase information. The
sample application provides an example database (PurchaseDatabase.java); however, the example
database has been simplified for clarity and does not exhibit the security best practices that we
recommend. If you have a remote server, we recommend that you store purchase information on your
server instead of in a local database on a device. For more information about security best
practices, see <a href="../../../guide/market/billing/billing_best_practices.html">Security and
Design</a>.</p>

<p class="note"><strong>Note</strong>: If you store any purchase information on a device, be sure to
encrypt the data and use a device-specific encryption key. Also, if the purchase type for any of
your items is "unmanaged," we recommend that you back up the purchase information for these items to
a remote server or use Android's <a href="../../../guide/topics/data/backup.html">data
backup</a> framework to back up the purchase information. Backing up purchase information for
unmanaged items is important because unmanaged items cannot be restored by using the
<code>RESTORE_TRANSACTIONS</code> request type.</p>

<h3>Creating a user interface for selecting items</h3>

<p>You must provide users with a means for selecting items that they want to purchase. Android
Market provides the checkout user interface (which is where the user provides a form of payment and
approves the purchase), but your application must provide a control (widget) that invokes the
<code>sendBillingRequest()</code> method when a user selects an item for purchase.</p>

<p>You can render the control and trigger the <code>sendBillingRequest()</code> method any way you
want. The sample application uses a spinner widget and a button to present items to a user and
trigger a billing request (see <code>Dungeons.java</code>). The user interface also shows a list of
recently purchased items.</p>


    </div>

  <a href="#top" style="float:right">&uarr; Go to top</a>
  
    <p><a href="index.html">&larr; Back to In-app Billing</a></p>
  
  </div>

<div id="footer">


  <div id="copyright">
    
  Except as noted, this content is licensed under <a
  href="http://www.apache.org/licenses/LICENSE-2.0">Apache 2.0</a>. 
  For details and restrictions, see the <a href="../../../license.html">
  Content License</a>.
  </div>
  <div id="build_info">
    
  Android 4.0&nbsp;r1 - 17 Oct 2011 18:17

  </div>

  <div id="footerlinks">
    
  <p>
    <a href="http://www.android.com/terms.html">Site Terms of Service</a> -
    <a href="http://www.android.com/privacy.html">Privacy Policy</a> -
    <a href="http://www.android.com/branding.html">Brand Guidelines</a>
  </p>
  </div>

</div> <!-- end footer -->

</div><!-- end doc-content -->

</div> <!-- end body-content --> 

<script type="text/javascript">
init(); /* initialize android-developer-docs.js */
var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
</script>
<script type="text/javascript">
var pageTracker = _gat._getTracker("UA-5831155-1");
pageTracker._trackPageview();
</script>

</body>
</html>



